package com.huajx.core.udp;

import com.huajx.core.log.Log;
import com.huajx.core.util.MessageKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2019-09-17 14:19
 */
public class LocalUDPDataReciever {
    private static final String TAG = LocalUDPDataReciever.class.getSimpleName();
    private static final Logger logger = LoggerFactory.getLogger(TAG);
    private static LocalUDPDataReciever instance = null;
    private Thread thread = null;

    public static LocalUDPDataReciever getInstance() {
        if (instance == null)
            instance = new LocalUDPDataReciever();
        return instance;
    }

    public void startup() {
        this.thread = new Thread(new Runnable() {
            public void run() {
                try {
                    Log.i(TAG, "本地UDP端口侦听中，端口=" + "...");

                    //开始侦听
                    LocalUDPDataReciever.getInstance().udpListeningImpl();
                } catch (Exception eee) {
                    Log.w(TAG, "本地UDP监听停止了(socket被关闭了?)," + eee.getMessage(), eee);
                }
            }
        });
        this.thread.start();
    }

    private void udpListeningImpl() throws Exception {
        while (true) {
            byte[] data = new byte[34];
            // 接收数据报的包
            DatagramPacket packet = new DatagramPacket(data, data.length);

            DatagramSocket localUDPSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket();
            if ((localUDPSocket == null) || (localUDPSocket.isClosed()))
                continue;

            // 阻塞直到收到数据
            localUDPSocket.receive(packet);

            // 解析服务端发过来的数据
            String pFromServer = MessageKit.bytesToHex(data);//new String(packet.getData(), 0, packet.getLength(), "UTF-8");
            if(pFromServer.equals("7e,0,95,81,10,a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,1,d,")) {
                continue;
            }
//            logger.info("{},{}",localUDPSocket.getInetAddress(),localUDPSocket.getPort());
            logger.info("【NOTE】>>>>>> 收到服务端的消息：{}", pFromServer);
      
        }

    }
}